#coding:utf-8
'''
Created on 2017-04-28

@author: sandy
'''

import logging
from twisted.web import resource
from twisted.web.server import Site
from twisted.internet import reactor
from twisted.web.server import NOT_DONE_YET
from pycommon import Const, Utils
import sys
import json
import GameDb


ENCODING = u"UTF-8"

def returnErrorAsync(request, ret, error):
    result = {}
    result[u"ret"] = ret
    result[u"err"] = unicode(error)
    request.write(json.dumps(result).encode(ENCODING))
    request.finish()
    
def returnRetAsync(request, result):
    result[u"ret"] = Const.ERR_OK
    request.write(json.dumps(result).encode(ENCODING))
    request.finish()  
    
def buildError(ret, error):
    result = {}
    result[u"ret"] = ret
    result[u"err"] = unicode(error)
    return json.dumps(result).encode(ENCODING)
    
def buildRet(request, result):
    result[u"ret"] = Const.ERR_OK
    return json.dumps(result).encode(ENCODING) 

def payResult(request,result):
    orderId = 0
    payState = 2
    if payState == 2:
        logging.debug("payResult sucess")
        GameDb.instance.paySucess(orderId)
    else:
        logging.debug("")
    pass

class PageWeChatBill(resource.Resource):
    
    def __init__(self):
        self.handlermap = {}
        
    def register(self, handlername ,func):
        logging.info(u'PageWeChatBill.register() handlername=%s', handlername)
        if self.handlermap.get(handlername, None)!=None:
            raise KeyError(u'PageWeChatBill<%d> hanlder exist' % (handlername,))
        self.handlermap[handlername] = func

    def render_GET(self, request):
        try:
            return self.handleRequest(request)
        except Exception, e:
            logging.exception("render_GET")
            return buildError(Const.ERR_UNKNOWN, e)
            
    def render_POST(self, request):
        return buildError(Const.ERR_WAIT_AND_RETRY, u"")
    
    def handleRequest(self,request):
        request.setHeader('Access-Control-Allow-Origin', '*')
        request.setHeader('Access-Control-Allow-Methods', 'GET')
        request.setHeader('Access-Control-Allow-Headers', 'x-prototype-version,x-requested-with')
        request.setHeader('Access-Control-Max-Age', 2520) # 42 hours  
        signkey = '96e79218965eb72c92a549dd5a330112'
        method = request.args["method"][0]
        param = request.args["param"][0]
        sign = request.args["sign"][0]
        mysign = Utils.md5sumhex(method+'&'+param+'&'+signkey)
        if sign!=mysign:
            return buildError(Const.ERR_SIGN_VERIFY_WRONG, u"sign error")
        method = method.decode(ENCODING)
        param = param.decode(ENCODING)
        param = json.loads(param)
        func = self.handlermap.get(method, None)
        if not func:
            m = sys.modules['BillWeChatSite']
            func = getattr(m, method, None)
        if not func:
            return buildError(Const.ERR_UNKOWN_METHOD, u"unkown method : %s" % method)
        ret = func(request, param)       
        if ret != NOT_DONE_YET:
            return ret
        return NOT_DONE_YET

class WebSite(object):
    
    def __init__(self):
        self.port = None
        self.root = None
        self.regmap = {}
        
    def register(self, path, page):
        logging.info(u'WebSite.register() path=%s', path)
        if self.root:
            self.root.putChild(path, page)
        else:
            self.regmap[path] = page
    
    def start(self,webip = u'127.0.0.1',webport = 80):
        self.root = resource.Resource()
        self.root.putChild("billwechat", PageWeChatBill())
        for path,page in self.regmap.iteritems():
            self.root.putChild(path, page)
        self.regmap.clear()
        self.port = reactor.listenTCP(webport,Site(self.root),interface = webip)
    
    def stop(self):
        self.port.stopListening()
        pass
    
    
instance = WebSite()
